package main

import (
	"fmt"
	"io"
	"net"
	"net/rpc"
	"os"
	common "projRoot/commonLib"
)

var closingSignal chan bool = make(chan bool, 1)

var helperDone chan bool = make(chan bool)

func readyToClose() {
	// 键入回车, 立刻通知channel
	os.Stdin.Read(make([]byte, 1))
	closingSignal <- true

	for {
		TCP_conn, err := net.Dial("tcp", fmt.Sprintf(":%d", common.ServerPort))
		if err != nil {
			fmt.Printf("helper goroutine: 服务器已下线:%s\n", err)
			break
		}
		fmt.Println("退出goroutine:", TCP_conn.LocalAddr().String())
		TCP_conn.Close()
	}

	// time.Sleep(time.Second)
	fmt.Println("helper goroutine has exited√")
	helperDone <- true
}

func main() {
	// 1. 注册RCP函数
	err := rpc.RegisterName(common.ServiceName, new(common.MathService))
	if err != nil {
		panic(err)
	}
	err = rpc.RegisterName(common.LockServiceName, new(common.LockService))
	if err != nil {
		panic(err)
	}

	fmt.Println("RPC names registration")

	listening_state, err := net.Listen("tcp", fmt.Sprintf(":%d", common.ServerPort))
	if err != nil {
		panic(err)
	}
	fmt.Printf("Server was listening on port: %s\n", listening_state.Addr().String())

	// 按下回车即exit
	go readyToClose()

loop:
	for {
		TCP_conn, err := listening_state.Accept()
		if err != nil {
			panic(TCP_conn)
		} else {
			fmt.Printf("建立TCP连接with:%s \n", TCP_conn.RemoteAddr().String())
		}
		select {
		case <-closingSignal:
			{
				// TCP_conn.Close()
				listening_state.Close()
				break loop
			}
		default:
			{
				go func(conn io.ReadWriteCloser) {
					rpc.ServeConn(conn)
				}(TCP_conn)
			}
		}
	}

	<-helperDone
}
